<template>
<view class="container">
  <!-- 导航栏 -->
  <view class="nav-bar">
    <view 
      class="nav-item"
      :class="{active:currentView==='day'}"
      @click="switchView('day')"
    >
      今日活动
    </view>
    <view 
      class="nav-item"
      :class="{active:currentView==='week'}"
      @click="switchView('week')"
    >
      本周统计
    </view>
  </view>
  
  <!-- 今日活动视图 -->
  <view v-if="currentView==='day'" class="day-view">
    <!-- 活动概览卡片 -->
    <view class="card">
      <view class="card-header">
        <text class="title">今日活动数据</text>
        <view class="stats">
          <text class="stat-value">{{patientData.day.steps}}</text>
          <text class="stat-label">步数</text>
        </view>
      </view>
      
      <!-- 活动目标进度 -->
      <view class="progress-container">
        <view class="progress-info">
          <text class="progress-label">活动目标完成度</text>
          <text class="progress-value">{{patientData.day.progress}}%</text>
        </view>
        <view class="progress-bar">
          <view class="progress-fill" :style="{width: patientData.day.progress + '%'}"></view>
        </view>
        <text class="progress-tip">建议每日{{patientData.day.target}}步</text>
      </view>
      
      <!-- 活动数据汇总 -->
      <view class="activity-summary">
        <view class="summary-item">
          <text class="summary-value">{{patientData.day.distance}}</text>
          <text class="summary-label">活动距离</text>
        </view>
        <view class="summary-item">
          <text class="summary-value">{{patientData.day.activeMinutes}}</text>
          <text class="summary-label">活动时间</text>
        </view>
      </view>
    </view>
    
    <!-- 活动时段分布 -->
    <view class="card">
      <view class="card-header">
        <text class="title">活动时段分布</text>
      </view>
      <qiun-data-charts
        type="column"
        :opts="columnOpts"
        :chartData="hourlyData"
      />
    </view>
    
    <!-- 医生建议卡片 -->
    <view class="card advice-card">
      <view class="card-header">
        <text class="title">康复建议</text>
      </view>
      <text class="advice-text">{{patientData.day.advice}}</text>
    </view>
  </view>
  
  <!-- 本周统计视图 -->
  <view v-else class="week-view">
    <!-- 周活动趋势 -->
    <view class="card">
      <view class="card-header">
        <text class="title">本周活动趋势</text>
        <view class="stats">
          <text class="stat-value">{{patientData.week.avgSteps}}</text>
          <text class="stat-label">日均步数</text>
        </view>
      </view>
      <qiun-data-charts
        type="line"
        :opts="lineOpts"
        :chartData="weekTrendData"
      />
    </view>
    <!-- 周活动达标情况 -->
    <view class="card">
      <view class="card-header">
        <text class="title">本周达标情况</text>
      </view>
      <view class="compliance-grid">
        <view 
          class="compliance-day"
          v-for="(day,index) in patientData.week.days"
          :key="index"
          :class="{complete:day.complete}"
        >
          <text class="day-name">{{day.name}}</text>
          <text class="day-status">{{day.complete?'达标':'未达'}}</text>
        </view>
      </view>
    </view>
    
    <!-- 周活动汇总 -->
    <view class="card week-summary-card">
      <view class="summary-row">
        <view class="summary-col">
          <text class="summary-title">总步数</text>
          <text class="summary-main">{{patientData.week.totalSteps}}</text>
        </view>
        <view class="summary-col">
          <text class="summary-title">达标天数</text>
          <text class="summary-main">{{patientData.week.completeDays}}天</text>
        </view>
      </view>
      <view class="summary-row">
        <view class="summary-col">
          <text class="summary-title">最长活动</text>
          <text class="summary-main">{{patientData.week.longestActive}}分钟</text>
        </view>
        <view class="summary-col">
          <text class="summary-title">最佳表现</text>
          <text class="summary-main">{{patientData.week.bestDay}}</text>
        </view>
      </view>
    </view>
  </view>
</view>
</template>

<script setup>

import { ref, computed } from 'vue'
import { useHealthData } from '../store/modules/useHealthData';
import { onMounted } from 'vue';


const isLoading = ref(false)
const currentView = ref('day')

const patientData = {
  day: {
    steps: '2,856',
    progress: 57,
    target: '5,000',
    distance: '1.8公里',
    activeMinutes: '32',
    advice: "今日活动量已达到建议的57%，建议下午可适当增加10分钟散步，注意保持均匀的活动节奏。"
  },
  week: {
    avgSteps: '2,450',
    totalSteps: '17,150',
    completeDays: '3',
    longestActive: '45',
    bestDay: '3,210步',
    days: [
      {name: "周一", complete: false},
      {name: "周二", complete: true},
      {name: "周三", complete: false},
      {name: "周四", complete: true},
      {name: "周五", complete: false},
      {name: "周六", complete: true},
      {name: "周日", complete: false}
    ]
  }
}

const columnOpts = {
  color: ["#3B82F6"],
  padding: [15,15,0,5],
  enableScroll: false,
  legend: {
    show: false
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED"
  },
  yAxis: {
    gridType: "dash",
    dashLength: 4,
    data: [{
      min: 0,
      axisLineColor: "#E4E7ED",
      splitLineColor: "#F7F8FA"
    }]
  },
  extra: {
    column: {
      type: "group",
      width: 15,
      categoryGap: 5,
      activeBgColor: "#000000",
      activeBgOpacity: 0.08
    }
  }
}

const lineOpts = {
  color: ["#3B82F6"],
  padding: [15,15,0,5],
  enableScroll: false,
  legend: {
    show: false
  },
  xAxis: {
    disableGrid: true,
    axisLineColor: "#E4E7ED"
  },
  yAxis: {
    gridType: "dash",
    dashLength: 4,
    data: [{
      min: 0,
      axisLineColor: "#E4E7ED",
      splitLineColor: "#F7F8FA"
    }]
  },
  extra: {
    line: {
      type: "straight",
      width: 3,
      activeType: "hollow"
    }
  }
}

const hourlyData = computed(() => ({
  categories: ["6-8", "8-10", "10-12", "12-14", "14-16", "16-18", "18-20", "20-22"],
  series: [
    {
      name: "步数",
      data: [120, 280, 350, 180, 320, 450, 380, 210]
    }
  ]
}))

const weekTrendData = computed(() => ({
  categories: ["周一", "周二", "周三", "周四", "周五", "周六", "周日"],
  series: [
    {
      name: "步数",
      data: [1850, 3210, 2340, 2780, 1960, 3020, 2150]
    }
  ]
}))



// 数据处理函数
const processActivityData = (rawData, viewType) => {
  if (viewType === 'day') {
    // 按小时分组
    const hourlyBuckets = Array(8).fill(0); // 8个时间段
    const timeRanges = ["6-8", "8-10", "10-12", "12-14", "14-16", "16-18", "18-20", "20-22"];

    rawData.forEach((item) => {
      const hour = new Date(item.collectTime).getHours();
      const bucketIndex = Math.floor((hour - 6) / 2); // 每2小时一个时间段
      if (bucketIndex >= 0 && bucketIndex < hourlyBuckets.length) {
        hourlyBuckets[bucketIndex] += item.steps; // 累加步数
      }
    });

    return {
      categories: timeRanges,
      series: [
        {
          name: "步数",
          data: hourlyBuckets,
        },
      ],
    };
  } else if (viewType === 'week') {
    // 按天分组
    const dailySteps = Array(7).fill(0); // 一周7天
    const weekDays = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];

    rawData.forEach((item) => {
      const dayIndex = new Date(item.collectTime).getDay(); // 获取星期几
      const mappedIndex = (dayIndex === 0 ? 6 : dayIndex - 1); // 将周日映射到最后
      dailySteps[mappedIndex] += item.steps; // 累加步数
    });

    return {
      categories: weekDays,
      series: [
        {
          name: "步数",
          data: dailySteps,
        },
      ],
    };
  }
};

const fetchActivityData = async (viewType) => {
  isLoading.value = true;
  try {
    const healthStore = useHealthData();
    const userId = 1; // 替换为实际用户ID
    const startDate = viewType === 'day'
      ? new Date().toISOString().split('T')[0]
      : new Date(new Date().setDate(new Date().getDate() - 7)).toISOString().split('T')[0];
    const endDate = new Date().toISOString().split('T')[0];

    const response = await healthStore.fetchHistoryData(userId, startDate, endDate);
    const rawData = response.data; // 假设返回的数据在 `data` 字段中

    if (viewType === 'day') {
      hourlyData.value = processActivityData(rawData, 'day');
    } else if (viewType === 'week') {
      weekTrendData.value = processActivityData(rawData, 'week');
    }
  } catch (error) {
    console.error('获取活动数据失败:', error);
  } finally {
    isLoading.value = false;
  }
};




const switchView = (view) => {
  currentView.value = view
  // fetchActivityData(view);
}

onMounted(() => {
  // 初始化时加载今日活动数据
  // fetchActivityData('day');
});


</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
  background-color: #F7F8FA;
  min-height: 100vh;
}

/* 导航栏样式 */
.nav-bar {
  display: flex;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.04);
  
  .nav-item {
    flex: 1;
    text-align: center;
    padding: 24rpx 0;
    font-size: 28rpx;
    color: #666;
    position: relative;
    transition: all 0.3s;
    
    &.active {
      color: #3B82F6;
      font-weight: 500;
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 80rpx;
        height: 4rpx;
        background-color: #3B82F6;
        border-radius: 2rpx;
      }
    }
  }
}

/* 卡片通用样式 */
.card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  padding: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.04);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  
  .title {
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
  }
  
  .stats {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    
    .stat-value {
      font-size: 28rpx;
      font-weight: 500;
      color: #3B82F6;
    }
    
    .stat-label {
      font-size: 24rpx;
      color: #999;
      margin-top: 4rpx;
    }
  }
}

/* 进度条样式 */
.progress-container {
  margin: 30rpx 0;
  
  .progress-info {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10rpx;
    
    .progress-label {
      font-size: 26rpx;
      color: #666;
    }
    
    .progress-value {
      font-size: 26rpx;
      color: #3B82F6;
      font-weight: 500;
    }
  }
  
  .progress-bar {
    height: 12rpx;
    background-color: #F0F0F0;
    border-radius: 6rpx;
    overflow: hidden;
    
    .progress-fill {
      height: 100%;
      background: linear-gradient(90deg, #3B82F6, #60A5FA);
      border-radius: 6rpx;
      transition: width 0.5s ease;
    }
  }
  
  .progress-tip {
    display: block;
    font-size: 24rpx;
    color: #999;
    text-align: right;
    margin-top: 8rpx;
  }
}

/* 活动数据汇总 */
.activity-summary {
  display: flex;
  justify-content: space-around;
  margin-top: 30rpx;
  
  .summary-item {
    text-align: center;
    
    .summary-value {
      font-size: 36rpx;
      font-weight: 500;
      color: #333;
      display: block;
    }
    
    .summary-label {
      font-size: 24rpx;
      color: #999;
    }
  }
}

/* 医生建议卡片 */
.advice-card {
  .advice-text {
    font-size: 26rpx;
    color: #666;
    line-height: 1.6;
  }
}

/* 周达标情况网格 */
.compliance-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 20rpx;
  margin-top: 20rpx;
  
  .compliance-day {
    text-align: center;
    padding: 16rpx 0;
    border-radius: 8rpx;
    background-color: #F7F8FA;
    
    &.complete {
      background-color: #EFF6FF;
      
      .day-status {
        color: #3B82F6;
      }
    }
    
    .day-name {
      font-size: 24rpx;
      color: #666;
      display: block;
    }
    
    .day-status {
      font-size: 24rpx;
      color: #999;
      display: block;
      margin-top: 8rpx;
    }
  }
}

/* 周活动汇总卡片 */
.week-summary-card {
  .summary-row {
    display: flex;
    margin-bottom: 20rpx;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .summary-col {
    flex: 1;
    
    &:first-child {
      margin-right: 20rpx;
    }
    
    .summary-title {
      font-size: 26rpx;
      color: #999;
      display: block;
      margin-bottom: 8rpx;
    }
    
    .summary-main {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
    }
  }
}

/* 图表容器 */
qiun-data-charts {
  display: block;
  width: 100%;
  height: 400rpx;
}
</style>